﻿using Dapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using zhangmenren.Db;
using zhangmenren.Models;
using zhangmenren.ViewModel;

namespace zhangmenren.Repository
{
    public class RealRepository:BaseRepository
    {

        public int Add(RealEntity entity)
        {
            string sql = @"INSERT INTO Real 
                            (UserId
                            ,Name
                            ,CarNO
                            ,CarImgZ
                            ,CarImgF,PhotoZ,PhotoF
                            ,State,AddDT,UpDT)
                        VALUES
                            (@UserId
                            ,@Name
                            ,@CarNO
                            ,@CarImgZ
                            ,@CarImgF,@PhotoZ,@PhotoF
                            ,@State,GETDATE(),GETDATE())";
            return Execute(connection => connection.Execute(sql, entity));
        }

        public IEnumerable<RealMode> Select()
        {
            // string sql = @"SELECT ID,Mobile,UserName,Head,Signature,Introduction FROM [User]";
            string sql = @"SELECT [Real].*,(SELECT UserName FROM [User] Where [Real].UserId = [User].Id) AS UserName FROM [Real]";
            return Execute(connection => connection.Query<RealMode>(sql));
        }

        public IEnumerable<RealEntity> FindById(int id)
        {
            // string sql = @"SELECT ID,Mobile,UserName,Head,Signature,Introduction FROM [User]";
            string sql = @"SELECT Id,UserId,Name,CarNO,CarImgZ,CarImgF,PhotoZ,PhotoF,State,AddDT FROM Real WHERE Id=@Id";
            return Execute(connection => connection.Query<RealEntity>(sql,new {Id=id }));
        }

        public IEnumerable<RealEntity> FindByUserId(int userid)
        {
            // string sql = @"SELECT ID,Mobile,UserName,Head,Signature,Introduction FROM [User]";
            string sql = @"SELECT Id,UserId,Name,CarNO,CarImgZ,CarImgF,PhotoZ,PhotoF,State,AddDT FROM Real WHERE UserId=@UserId";
            return Execute(connection => connection.Query<RealEntity>(sql, new { UserId = userid }));
        }

        public int UpState(int id,int state)
        {
            // string sql = @"SELECT ID,Mobile,UserName,Head,Signature,Introduction FROM [User]";
            string sql = @"UPDATE Real SET State = @State WHERE Id=@Id";
            return Execute(connection => connection.Execute(sql, new { Id = id,State=state }));
        }

        public int Del(int id)
        {
            string sql = @"DELETE FROM Real WHERE Id = @Id";
            return Execute(connection => connection.Execute(sql, new { Id = id }));
        }
    }
}
